package cj.web.marriageSC.controllers;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ExportExcel;
import cj.utils.sc.KDNiaoUtil;
import cj.web.admin.constants.KDAddressAreaEnum;
import cj.web.admin.constants.KDAddressStreetEnum;
import cj.web.admin.constants.KDBookingStatusEnum;
import cj.web.admin.constants.KDOutputTypeEnum;
import cj.web.admin.constants.MemuEnum;
import cj.web.admin.domain.KDBookingCard;
import cj.web.admin.domain.UserInfo;
import cj.web.login.controllers.BaseController;
import cj.web.marriage.constants.MarriageSCIsInvoiceEnum;
import cj.web.marriage.constants.MarriageSCOrderStatusEnum;
import cj.web.marriage.constants.SCShipperCodeEnum;
import cj.web.marriageSC.dao.SCOrderDAO;
import cj.web.marriageSC.dao.SCSellerDAO;
import cj.web.marriageSC.domain.SCOrder;
import cj.web.marriageSC.domain.SCSeller;

@Path("/order")
public class SCOrderController extends BaseController {

	private static Logger logger = Logger.getLogger(SCOrderController.class
			.getName());

	@Autowired
	private SCOrderDAO orderDao;
	@Autowired
	private SCSellerDAO sellerDao;

	@Get("show")
	public String show(Model model, SCOrder order, HttpServletRequest request) {
		model.add("InvoiceEnum", EnumSet.allOf(MarriageSCIsInvoiceEnum.class));
		model.add("StatusEnum", EnumSet.allOf(MarriageSCOrderStatusEnum.class));
		model.add("ShipperEnum", EnumSet.allOf(SCShipperCodeEnum.class));
		model.add("MemuEnum", MemuEnum.marriagescorder);
		return "/views/marriageSC/orderList.vm";
	}

	@Post("list")
	public String list(Model model, SCOrder order, HttpServletRequest request) throws Exception {
		UserInfo user = returnSessionObj(request);
		String acount = user.getAccount();
		int userId = user.getId();
		SCSeller seller = sellerDao.queryByUserInfoId(userId);

		if (seller != null) {
			order.setSellerId(seller.getId());
		}

		if (Constants.ADMIN.equals(acount)) { // admin账户可看到所有的
			order.setSellerId(-1);
		}
		
		if( !"".equals(order.getCreateAt()) ){
			String createAtEnd = timeAddNDays(order.getCreateAt(), DateUtils.DATE_SMALL_STR, 1);
			order.setUpdateAt(createAtEnd);
		}

		List<SCOrder> objs = orderDao.queryBySellerId(order);
		int size = orderDao.sizeBySellerId(order);

		JSONObject jo = new JSONObject();
		jo.put("data", objs);
		jo.put("draw", order.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}

	@Get("output")
	public void output(Model model, SCOrder order,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String sheetName = "商城订单";
		String title = URLEncoder.encode(sheetName, "UTF-8"); // 进行转码，使其支持中文文件名
		response.setContentType("application/vnd.ms-excel"); // 生成提示信息
		response.setHeader("content-disposition", "attachment;filename="
				+ title + ".xls");
		OutputStream fOut = response.getOutputStream();

		List<Map> dataset = null;
		ExportExcel<SCOrder> ex = new ExportExcel<SCOrder>();

		String[] headers = { "订单号", "商家名称", "订单总价", "收件人", "收件人电话", "收件人地址",
				"发票类型", "发票抬头", "留言", "快递公司", "快递单号", "订单状态", "微信支付单号", "下单时间" };
		String[] fields = { "orderNo", "sellerName", "discntPrice",
				"receiverName", "receiverPhone", "receiverAddress",
				"isInvoice", "invoiceHead", "memo", "expressCom",
				"expressBill", "status", "wxTradeNo", "createAt" };

		UserInfo user = returnSessionObj(request);
		String acount = user.getAccount();
		int userId = user.getId();
		SCSeller seller = sellerDao.queryByUserInfoId(userId);
		if (seller != null) {
			order.setSellerId(seller.getId());
		}
		if (Constants.ADMIN.equals(acount)) { // admin账户可看到所有的
			order.setSellerId(-1);
		}
		
		if( !"".equals(order.getCreateAt()) ){
			String createAtEnd = timeAddNDays(order.getCreateAt(), DateUtils.DATE_SMALL_STR, 1);
			order.setUpdateAt(createAtEnd);
		}
		
		dataset = orderDao.outputBySellerId(order);

		for (Map map : dataset) {
			for (Object key : map.keySet()) {
				if(null == map.get(key)){
					map.put(key, "");
				}
			}
			String isInvoice = MarriageSCIsInvoiceEnum.getName(Integer.parseInt(map.get("isInvoice").toString()));
			map.put("isInvoice", isInvoice);
			String expressCom = SCShipperCodeEnum.getName(map.get("expressCom").toString());
			map.put("expressCom", expressCom);
			String strStatus = MarriageSCOrderStatusEnum.getName(Integer.parseInt(map.get("status").toString()));
			map.put("status", strStatus);
		}
		ex.exportExcel(sheetName, headers, fields, dataset, fOut,
				DateUtils.DATE_FULL_STR);
	}

	@Get("edit")
	public String edit(Model model, @Param("id") int id,
			HttpServletRequest request) {
		SCOrder obj = orderDao.queryById(id);
		model.add("obj", obj);
		model.add("MemuEnum", MemuEnum.marriagescorder);
		model.add("ShipperEnum", EnumSet.allOf(SCShipperCodeEnum.class));
		return "/views/marriageSC/orderEdit.vm";
	}

	@Post("update")
	public String update(Model model, SCOrder order, HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);

		String acount = returnSessionObj(request).getAccount();
		order.setUpdateUser(acount);
		order.setStatus(MarriageSCOrderStatusEnum.posted.getValue());// 订单状态已发货

		try {
			orderDao.update(order);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		return "@" + jo.toString();
	}

	@Get("chgXprBill")
	public String chgXprBill(Model model, @Param("id") int id,
			HttpServletRequest request) {
		SCOrder obj = orderDao.queryById(id);
		model.add("obj", obj);
		model.add("MemuEnum", MemuEnum.marriagescorder);
		model.add("ShipperEnum", EnumSet.allOf(SCShipperCodeEnum.class));
		return "/views/marriageSC/orderChgXpr.vm";
	}

	@Post("chgXpr")
	public String chgXpr(Model model, SCOrder order, HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);

		String acount = returnSessionObj(request).getAccount();
		order.setUpdateUser(acount);

		try {
			orderDao.chgXprBill(order);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		return "@" + jo.toString();
	}

	@Get("logist")
	public String logist(Model model, @Param("id") int id) throws Exception {
		SCOrder order = orderDao.queryById(id);
		if (order != null) {
			String expressCom = order.getExpressCom();
			String expressBill = order.getExpressBill();

			model.add("expressName", SCShipperCodeEnum.getName(expressCom));
			model.add("expressBill", expressBill);

			KDNiaoUtil api = new KDNiaoUtil();
			String result = api.getOrderTracesByJson(expressCom, expressBill);

			JSONObject jo = new JSONObject().fromObject(result);
			// 查询成功
			Boolean success = jo.getBoolean("Success");
			if (success) {
				Object reaObj = jo.get("Reason");
				if (reaObj == null) {
					// 物流路线
					JSONArray jslis = jo.getJSONArray("Traces");
					List<Map> list = JSONArray.toList(jslis, Map.class);// 过时方法
					Collections.reverse(list);

					model.add("list", list);
				} else {
					model.add("reason", reaObj.toString());
				}
			} else {
				Object reaObj = jo.get("Reason");
				if (reaObj != null) {
					model.add("reason", reaObj.toString());
				}
			}

		}

		model.add("MemuEnum", MemuEnum.marriagescorder);
		return "/views/marriageSC/logistics.vm";
	}

	@Get("finish")
	// 买家已收货
	public String finish(Model model, @Param("id") int id) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		SCOrder order = orderDao.queryById(id);
		if (order != null) {
			orderDao.setStatus(id, MarriageSCOrderStatusEnum.finish.getValue());
		}

		return "@" + jo.toString();
	}
	
	// 买家已批量收货
	@Get("mutiFinish")
	public String mutiFinish(Model model, @Param("id") List<Integer> ids) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if (ids != null && ids.size() > 0) {
			orderDao.mutiSetStatus(ids, MarriageSCOrderStatusEnum.finish.getValue());
		}

		return "@" + jo.toString();
	}

	@Get("delete")
	// 买家已收货
	public String delete(Model model, @Param("id") int id,
			HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		SCOrder order = orderDao.queryById(id);
		if (order != null) {
			String acount = returnSessionObj(request).getAccount();
			order.setUpdateUser(acount);
			orderDao.delete(order);
		}

		return "@" + jo.toString();
	}

	private String timeAddNDays(String createAt, String pattern, int days) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat(pattern);
		Date createAtDate = df.parse(createAt);
		
		Calendar cl = Calendar.getInstance();
		cl.setTime(createAtDate);
		cl.add(Calendar.DATE, days);
		
		return df.format(cl.getTime());
	}
}
